import React, { ReactNode, useEffect, useState } from 'react';
import { Modal, Form } from 'antd';

interface ModalFormProps {
	visible: boolean;
	onCreate: (values: any) => void;
	onCancel: () => void;
	loading?: boolean;
	children?: any;
	title?: string;
	formData?: Record<string, any>;
	width?: number;
}

const ModalForm = (props: ModalFormProps): JSX.Element => {
	const [form] = Form.useForm();
	const [, updateState] = useState<any>();
	const forceUpdate = React.useCallback(() => updateState({}), []);

	useEffect(() => {
		if (props.formData) {
			form.setFieldsValue(props.formData);
			// forceUpdate()
		}
	}, [props]);

	return (
		<Modal
			confirmLoading={props.loading}
			destroyOnClose={true}
			width={props.width || 680}
			visible={props.visible}
			title={props.title}
			okText="确定"
			cancelText="取消"
			onCancel={() => {
				form.resetFields();
				props.onCancel();
			}}
			onOk={() => {
				form.validateFields()
					.then((values) => {
						props.onCreate(values);
						// form.resetFields();
					})
					.catch((info) => {
						console.log('Validate Failed:', info);
					});
			}}
		>
			<Form labelCol={{ span: 5 }} wrapperCol={{ span: 19 }} form={form} layout="horizontal" name="form_in_modal">
				{props.children && Object.prototype.toString.call(props.children) === '[object Function]'
					? props.children(form)
					: props.children}
			</Form>
		</Modal>
	);
};

export default ModalForm;
